package com.github.chxiaowu.common;

import java.io.IOException;
import java.lang.reflect.Type;

import org.bson.types.ObjectId;

import com.alibaba.fastjson.serializer.JSONSerializer;
import com.alibaba.fastjson.serializer.ObjectSerializer;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.SerializeWriter;
import com.alibaba.fastjson.serializer.SerializerFeature;

/**
 * fastjson ObjectId 自定义序列化
 * 
 * @author chenhua
 *
 */
public class ObjectIdSerializer implements ObjectSerializer {
	public final static ObjectIdSerializer INSTANCE = new ObjectIdSerializer();

	public static SerializeConfig config = new SerializeConfig();
	static {
		config.put(ObjectId.class, ObjectIdSerializer.INSTANCE);
	}

	@Override
	public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features)
			throws IOException {
		SerializeWriter out = serializer.getWriter();

		if (object == null) {
			if (out.isEnabled(SerializerFeature.WriteNullStringAsEmpty)) {
				out.writeString("");
			} else {
				out.writeNull();
			}
			return;
		}
		out.writeString(object.toString());

	}

}
